package com.bawei.property.vm

import androidx.lifecycle.viewModelScope
import com.bawei.common.vm.BaseViewModel
import com.bawei.property.entity.ParkApplyResultEntity
import com.bawei.property.intent.ParkApplyViewIntent
import com.bawei.property.model.ParkApplyRepository
import com.bawei.property.state.ParkApplyUiState
import com.bawei.property.state.ParkUiState
import com.blankj.utilcode.util.EncryptUtils
import com.blankj.utilcode.util.GsonUtils
import com.tencent.mmkv.MMKV
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import javax.inject.Inject

/**
 * Author: Jason Zhang
 * Date: 2024/12/24
 * Desc:
 */
@HiltViewModel
class ParkApplyViewModel @Inject constructor(private val mRepository: ParkApplyRepository) : BaseViewModel<ParkApplyViewIntent>(){

    private val _uiState = MutableStateFlow<ParkApplyUiState>(ParkApplyUiState.NoneState)
    val uiState: StateFlow<ParkApplyUiState> = _uiState.asStateFlow()
//    private val mRepository = ParkApplyRepository()
//    @Inject lateinit var mRepository: ParkApplyRepository


    override fun dispatchIntent(intent: ParkApplyViewIntent) {
       when(intent){
           is ParkApplyViewIntent.LoadParkApplyList -> loadParkApplyList()
       }
    }


    private fun loadParkApplyList(){
        viewModelScope.launch(Dispatchers.IO) {
            try {
                var userId = MMKV.defaultMMKV().decodeInt("userId")
                var time = (System.currentTimeMillis() / 1000).toString()
                var sign = EncryptUtils.encryptMD5ToString("${userId}${time}tamboo").lowercase()
                var mapParams = mapOf("userId" to userId, "time" to time, "sign" to sign)
                var paramsJson = GsonUtils.toJson(mapParams)
                var reqBody = paramsJson.toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())
                var result = mRepository.getParkApplyList(reqBody)
                if (result.statuesCode == "200"){
                    _uiState.value = ParkApplyUiState.LoadParkApplyListSuccess(result.getValues())
                } else{
                    _uiState.value = ParkApplyUiState.LoadParkApplyListFail(result.msg ?: "接口请求失败！")
                }
            } catch (e: Exception){
                e.printStackTrace()

            } finally {
                cancel()
            }
        }
    }


}